/**
 * Created by admin on 2017/5/3.
 * 根据传入的url和savePath，以及fileName，将Url所对应的资源以fileName文件名保存到savePath文件夹中
 */
const http = require('http');
const request = require('request');
const fs = require('fs');
// path模块，可以生产相对和绝对路径
const path = require('path');
const logUtil = require('../utils/log_util');

/**
 * 文件下载
 * @param url
 * @param fileName
 * @param savePath
 * @returns {Promise}
 */

exports.saveImageDataToFileByUrl = (url, fileName, savePath) => {
  logUtil.info(`fileName:${fileName}`);
    // 将文件名中的“/”,替换为“_”
  // fileName = fileName.replace(new RegExp('/', 'gm'), '-');
  fileName = fileName.split('/')[fileName.split('/').length - 1];
  // logUtil.info(`fileName:${fileName}`);
  return new Promise((resolve, reject) => {
    http.get(url, (res) => {
      let imgData = '';
      res.setEncoding('binary');
      res.on('data', (chunk) => {
        imgData += chunk;
      });
      res.on('end', () => {
        fs.writeFile(path.join(savePath, fileName), imgData, 'binary', (err) => {
          if (err) {
            console.log(`down fail!  ${fileName}`);
            // console.dir(err);
            reject(`XXXXX fail!  ${fileName}`);
          } else {
            console.log(`down success!  ${fileName}`);
            // update image set isdownload=1 where id=?

            resolve(`XXXX success!  ${fileName}`);
          }
        });
      });
    }).on('error', () => {
      reject(`XXXXX fail!  ${fileName}`);
    });
  });
};


/**
 * 将url图片转换为64位字符串
 * @param url
 */
exports.getBase64BitDataByUrl = url =>
   new Promise((resolve, rej) => {
     if (url) {
       http.get(url, (res) => {
         let imgData = '';
         res.setEncoding('binary');
         res.on('data', (chunk) => {
           imgData += chunk;
         });
         res.on('end', () => {
           // logUtil.info(`data:image/jpeg;base64,${new Buffer(imgData).toString('base64')}`);
           resolve(`data:image/jpeg;base64,${new Buffer(imgData).toString('base64')}`);
         });
       }).on('error', (err) => {
         rej(err);
       });
     } else {
       resolve(null);
     }
   });


/**
 * 将Url图片提交Post请求
 * @param url
 * @param fileName
 */
exports.toPostDataByUrl = (url, fileName) => {
  logUtil.info(`fileName:${fileName}`);
    // 将文件名中的“/”,替换为“_”
  fileName = fileName.replace(new RegExp('/', 'gm'), '-');
  logUtil.info(`fileName:${fileName}`);
  request
      .get(url)
      .on('response', (response) => {
        console.log(response.statusCode); // 200
        console.log(response.headers['content-type']); // 'image/png'
      })
      .pipe(request.post('project/saveImage?f=image.jpg'));
};

